package site.wanjiahao.set;

import site.wanjiahao.list.ArrayList;
import site.wanjiahao.list.ArrayListOptimize;
import site.wanjiahao.list.List;

/**
 * 使用动态数组，构造集合
 * @param <E>
 */
public class ListOptimizeSet<E> implements Set<E>{

    private final List<E> list = new ArrayListOptimize<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean contains(E ele) {
        return list.contains(ele);
    }

    @Override
    public void add(E ele) {
        int index = list.indexOf(ele);
        if (index != List.NOT_FOUND_ELEMENT) {
            // 覆盖
            list.set(index, ele);
        } else {
            list.add(ele);
        }
    }

    @Override
    public void remove(E ele) {
        int index = list.indexOf(ele);
        if (index != List.NOT_FOUND_ELEMENT) {
            list.remove(index);
        }
    }

    @Override
    public void traversal(Consumer<E> consumer) {
        for (int i = 0; i < list.size(); i++) {
            if (consumer.visit(list.get(i))) return;
        }
    }
}
